package com.basaji.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * This class is an implementation of {@link Filter filter} to distinguish
 * requests from wap.hozom.com and requests from www.hozom.com. Because the
 * default homepages of wap and www are different.
 * 
 * @author James
 * 
 */
public final class UrlFilter implements Filter {

	private static final Logger LOG = Logger.getLogger(UrlFilter.class);
    /**
     * {@inheritDoc}
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String url = httpRequest.getRequestURL().toString();
        
        //LOG.debug("url:"+url);
        
        RequestDispatcher dispatcher = null;
        String urlLowerCase = url.toLowerCase();
        
        String domain = null;
        
        String[] urls = urlLowerCase.split("\\.");
        
        if(urls.length>0 && urls[0].startsWith("http://")){
        	domain = urls[0].substring(7,urls[0].length());
        }else{
        	domain = urls[0];
        }
        if(urlLowerCase.trim().endsWith("/") && !"www".equals(domain) && !domain.startsWith("localhost") ){
        	dispatcher = request.getRequestDispatcher("/a/"+domain+"/index.shtml");
        	dispatcher.forward(request, response);
        }else if(!"www".equals(domain) && urlLowerCase.trim().endsWith(".shtml") && !urlLowerCase.trim().startsWith("http://localhost")) {
           dispatcher = request.getRequestDispatcher("/a/"+domain+"/"+ httpRequest.getRequestURI());
            dispatcher.forward(request, response);
        }  else {
            chain.doFilter(request, response);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void init(FilterConfig arg0) throws ServletException {
        // EMPTY
    }

    /**
     * 
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
        // EMPTY
    }
}